package com.pfsbuilder.Dialogs;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Vector;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;

import com.pfsbuilder.CommonLib;
import com.pfsbuilder.Library;
import com.pfsbuilder.PExceptionDialog;
import com.pfsbuilder.PIni;
import com.pfsbuilder.XMLHelper;

@SuppressWarnings("serial")
public class OpenDialog extends JDialog implements Runnable {
	BorderLayout borderLayout1 = new BorderLayout();
	JPanel panel1 = new JPanel();
	JPanel panel2 = new JPanel();
	JButton pOpenButton = new JButton();
	JPanel filePanel = new JPanel();
	JButton openPFSButton = new JButton();
	JLabel pFileLabel = new JLabel();
	public JLabel pfsFileLabel = new JLabel();
	private JLabel statusLabel;
	private JPanel panel9;
	BorderLayout borderLayout2 = new BorderLayout();
	JPanel panel7 = new JPanel();
	JLabel jLabel1 = new JLabel();
	public JLabel pProjectFileLabel = new JLabel();
	JButton selectProjectFileButton = new JButton();
	BorderLayout borderLayout3 = new BorderLayout();
	PIni ini = new PIni("Setting.ini");
	JPanel panel8 = new JPanel();
	JLabel label4 = new JLabel();
	public JLabel tempDirectoryLabel = new JLabel();
	JButton selectTempDirectoryButton = new JButton();
	BorderLayout borderLayout4 = new BorderLayout();
	JPanel panel3 = new JPanel();
	JLabel label1 = new JLabel();
	JPanel panel4 = new JPanel();
	public JTextField partitionOffsetTextField = new JTextField();
	public JRadioButton radioButton1 = new JRadioButton();
	JPanel panel5 = new JPanel();
	Border border1 = BorderFactory.createEmptyBorder(10, 10, 10, 10);
	public JComboBox offsetComboBox = new JComboBox();
	JButton searchButton = new JButton();
	JProgressBar progressBar1 = new JProgressBar();
	public JRadioButton radioButton2 = new JRadioButton();
	BorderLayout borderLayout5 = new BorderLayout();
	BorderLayout borderLayout6 = new BorderLayout();
	JPanel panel6 = new JPanel();
	BorderLayout borderLayout7 = new BorderLayout();
	ButtonGroup buttonGroup1 = new ButtonGroup();
	public boolean isCancel = true;
	Vector<HashMap> historyVector = XMLHelper.xmltoVector("history.xml", "/history/record");
	JComboBox historyComboBox = new JComboBox();

	public OpenDialog(Frame owner) {
		super(owner, true);
		this.getContentPane().setLayout(borderLayout1);
		pOpenButton.addActionListener(new POpenDialog_pOpenButton_actionAdapter(this));
		openPFSButton.setText("...");
		openPFSButton.addActionListener(new POpenDialog_pOpenPFSButton_actionAdapter(this));
		pFileLabel.setPreferredSize(new Dimension(100, 20));
		pFileLabel.setHorizontalAlignment(SwingConstants.LEFT);
		pFileLabel.setText("File :");
		pfsFileLabel.setPreferredSize(new Dimension(100, 20));
		pfsFileLabel.setHorizontalAlignment(SwingConstants.LEFT);
		pfsFileLabel.setText("");
		filePanel.setBorder(new EmptyBorder(5, 5, 5, 5));
		filePanel.setLayout(borderLayout2);
		jLabel1.setPreferredSize(new Dimension(100, 20));
		jLabel1.setText("Project file :");
		selectProjectFileButton.setText("...");
		selectProjectFileButton.addActionListener(new POpenDialog_pSelectProjectFileButton_actionAdapter(this));
		panel7.setBorder(new EmptyBorder(5, 5, 5, 5));
		panel7.setLayout(borderLayout3);
		label4.setPreferredSize(new Dimension(100, 20));
		label4.setText("Temp directory :");
		selectTempDirectoryButton.setText("...");
		selectTempDirectoryButton.addActionListener(new POpenDialog_pSelectTempDirectoryButton_actionAdapter(this));
		panel8.setBorder(new EmptyBorder(5, 5, 5, 5));
		panel8.setLayout(borderLayout4);
		label1.setHorizontalAlignment(SwingConstants.CENTER);
		label1.setText("Partition offset  :");
		partitionOffsetTextField.setText("0");
		radioButton1.setSelected(true);
		radioButton1.addActionListener(new POpenDialog_JRadioButton1_actionAdapter(this));
		offsetComboBox.setEnabled(false);
		offsetComboBox.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent evt) {
				pOffsetComboBoxMouseClicked(evt);
			}
		});
		searchButton.setEnabled(false);
		searchButton.setText("Search");
		searchButton.addActionListener(new POpenDialog_pSearchButton_actionAdapter(this));
		progressBar1.setVisible(false);
		panel5.setLayout(borderLayout5);
		panel4.setLayout(borderLayout6);
		panel6.setBorder(new EmptyBorder(5, 5, 5, 5));
		panel6.setLayout(borderLayout7);
		radioButton2.setEnabled(false);
		radioButton2.addActionListener(new POpenDialog_JRadioButton2_actionAdapter(this));
		BoxLayout JPanel1Layout = new BoxLayout(panel1, javax.swing.BoxLayout.Y_AXIS);
		panel1.setLayout(JPanel1Layout);
		this.getContentPane().add(panel1, java.awt.BorderLayout.CENTER);
		panel1.setBorder(border1);
		panel1.add(filePanel);
		panel1.add(panel7);
		panel1.add(panel8);
		pOpenButton.setText("Open");
		pOpenButton.setEnabled(false);
		this.getContentPane().add(panel2, java.awt.BorderLayout.SOUTH);
		panel2.setBorder(border1);
		panel2.add(pOpenButton);
		panel8.add(label4, java.awt.BorderLayout.WEST);
		panel8.add(tempDirectoryLabel, java.awt.BorderLayout.CENTER);
		panel8.add(selectTempDirectoryButton, java.awt.BorderLayout.EAST);
		panel1.add(panel6);
		{
			panel9 = new JPanel();
			panel1.add(panel9);
			{
				statusLabel = new JLabel();
				panel9.add(statusLabel);
			}
		}
		panel7.add(jLabel1, java.awt.BorderLayout.WEST);
		panel7.add(pProjectFileLabel, java.awt.BorderLayout.CENTER);
		panel7.add(selectProjectFileButton, java.awt.BorderLayout.EAST);
		filePanel.add(pfsFileLabel, java.awt.BorderLayout.CENTER);
		filePanel.add(pFileLabel, java.awt.BorderLayout.WEST);
		filePanel.add(openPFSButton, java.awt.BorderLayout.EAST);
		panel2.add(pOpenButton);
		{
			DefaultComboBoxModel pHistoryComboBoxModel = new DefaultComboBoxModel();
			pHistoryComboBoxModel.addElement("History");
			for (int x = historyVector.size() - 1; x >= 0; x--) {
				pHistoryComboBoxModel.addElement(historyVector.get(x).get("date"));
			}
			panel2.add(historyComboBox);
			historyComboBox.setModel(pHistoryComboBoxModel);
			historyComboBox.setPreferredSize(new java.awt.Dimension(188, 23));
			historyComboBox.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent evt) {
					pHistoryComboBoxActionPerformed(evt);
				}
			});
		}
		panel5.add(progressBar1, java.awt.BorderLayout.NORTH);
		panel5.add(radioButton2, java.awt.BorderLayout.WEST);
		panel5.add(offsetComboBox, java.awt.BorderLayout.CENTER);
		panel5.add(searchButton, java.awt.BorderLayout.EAST);
		BoxLayout JPanel3Layout = new BoxLayout(panel3, javax.swing.BoxLayout.Y_AXIS);
		panel3.setLayout(JPanel3Layout);
		panel3.add(panel4);
		panel4.add(partitionOffsetTextField, java.awt.BorderLayout.CENTER);
		partitionOffsetTextField.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent evt) {
				jPartitionOffsetTextFieldMouseClicked(evt);
			}
		});
		panel4.add(radioButton1, java.awt.BorderLayout.WEST);
		panel3.add(panel5);
		panel6.add(label1, java.awt.BorderLayout.WEST);
		panel6.add(panel3, java.awt.BorderLayout.CENTER);
		tempDirectoryLabel.setText(new File("temp").getAbsolutePath());
		setTitle("Open PFS Image");
		setSize(600, 300);
		CommonLib.centerDialog(this);
		buttonGroup1.add(radioButton2);
		buttonGroup1.add(radioButton1);
	}

	private void checkPOpenButton() {
		if (!this.pfsFileLabel.getText().equals("") && !this.pProjectFileLabel.getText().equals("") && !this.tempDirectoryLabel.getText().equals("")) {
			pOpenButton.setEnabled(true);
		} else {
			pOpenButton.setEnabled(false);
		}
	}

	public void pOpenButton_actionPerformed(ActionEvent e) {
		isCancel = false;
		setVisible(false);

		// save to history.xml
		String pfs_file = "";
		String project_file = "";
		String temp_directory = "";
		String offset = "";
		if (historyVector.size() > 0) {
			HashMap hashmap = historyVector.get(historyVector.size() - 1);
			pfs_file = CommonLib.empty(hashmap.get("pfs_file"));
			project_file = CommonLib.empty(hashmap.get("project_file"));
			temp_directory = CommonLib.empty(hashmap.get("temp_directory"));
			offset = CommonLib.empty(hashmap.get("offset"));
		}
		if (historyVector.size() == 0 || (historyVector.size() > 0 && (!pfs_file.equals(pfsFileLabel.getText()) || !project_file.equals(pProjectFileLabel.getText())
				|| !temp_directory.equals(tempDirectoryLabel.getText()) || ((radioButton1.isSelected() && !offset.equals(partitionOffsetTextField.getText()))
						|| (radioButton2.isSelected() && !offset.equals(CommonLib.empty(offsetComboBox.getSelectedItem()))))))) {
			HashMap newHashmap = new HashMap();
			newHashmap.put("date", new SimpleDateFormat("yyyy/MM/dd hh:mm:ss").format(new Date()));
			newHashmap.put("pfs_file", pfsFileLabel.getText());
			newHashmap.put("project_file", this.pProjectFileLabel.getText());
			newHashmap.put("temp_directory", this.tempDirectoryLabel.getText());
			if (radioButton1.isSelected()) {
				newHashmap.put("offset", partitionOffsetTextField.getText());
			} else {
				newHashmap.put("offset", this.offsetComboBox.getSelectedItem().toString().substring(0, this.offsetComboBox.getSelectedItem().toString().indexOf(":")));
			}
			historyVector.add(newHashmap);
			XMLHelper.vectorToXML("history.xml", "history", "record", historyVector);
		}
		// end save to history.xml
	}

	public void openPFSButton_actionPerformed(ActionEvent e) {
		File lastSelectedDirectory = new File(ini.getStringProperty("Last opened PFS image", "path", "."));
		if (!lastSelectedDirectory.exists()) {
			lastSelectedDirectory = new File(".");
		}
		JFileChooser jFileChooser = new JFileChooser();
		jFileChooser.setCurrentDirectory(lastSelectedDirectory);
		jFileChooser.setSize(500, 500);
		CommonLib.centerDialog(jFileChooser);
		if (jFileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
			ini.setStringProperty("Last opened PFS image", "path", jFileChooser.getCurrentDirectory().getAbsolutePath(), null);
			ini.save();

			radioButton2.setEnabled(true);

			pfsFileLabel.setText(jFileChooser.getSelectedFile().getAbsolutePath());
			if (pProjectFileLabel.getText().equals("")) {
				pProjectFileLabel.setText(jFileChooser.getSelectedFile().getParent() + File.separator + "project.ini");
			}
		}
		checkPOpenButton();
	}

	public void selectProjectFileButton_actionPerformed(ActionEvent e) {
		File lastOpenedProjectPath;
		JFileChooser jFileChooser = new JFileChooser();
		if (jFileChooser.getSelectedFile() != null) {
			lastOpenedProjectPath = new File(ini.getStringProperty("Last opened project file image", "path", jFileChooser.getSelectedFile().getParent()));
			if (!lastOpenedProjectPath.exists()) {
				lastOpenedProjectPath = new File(".");
			}
		} else {
			lastOpenedProjectPath = new File(".");
		}
		JFileChooser jFileChooser2 = new JFileChooser("Please select the project file");
		jFileChooser2.setCurrentDirectory(lastOpenedProjectPath);
		// JFileChooser2.setSelectedFilename("project.ini");
		jFileChooser2.setSize(500, 500);
		CommonLib.centerDialog(jFileChooser2);

		if (jFileChooser2.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
			ini.setStringProperty("Last opened project file image", "path", jFileChooser2.getSelectedFile().getAbsolutePath(), null);
			ini.save();
			pProjectFileLabel.setText(jFileChooser2.getSelectedFile().getAbsolutePath());
		}
		checkPOpenButton();
	}

	public void pSelectTempDirectoryButton_actionPerformed(ActionEvent e) {
		try {
			JFileChooser jFileChooser = new JFileChooser();
			File lastSelectedDirectory = new File(ini.getStringProperty("Last opened temp Directory", "path", "."));
			jFileChooser.setCurrentDirectory(lastSelectedDirectory);
			jFileChooser.setSize(500, 500);
			CommonLib.centerDialog(jFileChooser);

			if (jFileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
				tempDirectoryLabel.setText(jFileChooser.getSelectedFile().getAbsolutePath());
				ini.setStringProperty("Last opened temp Directory", "path", jFileChooser.getSelectedFile().getAbsolutePath(), null);
				ini.save();
			}
			checkPOpenButton();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public void run() {
		try {
			pOpenButton.setEnabled(false);
			File file = new File(pfsFileLabel.getText());
			progressBar1.setValue(0);
			progressBar1.setMaximum((int) (file.length() / 1024) - 1);
			progressBar1.setVisible(true);
			FileInputStream br = new FileInputStream(file);
			int bufferSize = 10 * 1024;
			int bytesRead = 1; // don't set to zero, danger, because br.read may
			// return zero
			byte buffer[] = new byte[bufferSize];

			for (int x = 0; x <= file.length() && bytesRead > 0; x += bytesRead) {
				if (searchButton.getText().equals("Search")) {
					break;
				} else {
					bytesRead = br.read(buffer);
					for (int y = 0; y < bytesRead - 1; y++) {
						int offset = x + y;
						if (Library.checkMagicNumber(buffer, y)) {
							if ((offset % (1024 * 1024)) == 0) {
								this.offsetComboBox.addItem(String.valueOf(offset) + ": " + offset / 1024 / 1024 + " MB");
							} else if (offset % 1024 == 0) {
								this.offsetComboBox.addItem(String.valueOf(offset) + ": " + offset / 1024 + " KB");
							} else {
								this.offsetComboBox.addItem(String.valueOf(offset));
							}
						}
					}

					progressBar1.setValue(x / 1024);
					statusLabel.setText("Searching " + CommonLib.convertFilesize(x));
				}
			}
			br.close();
		} catch (Exception ex) {
			ex.printStackTrace();
			if (com.pfsbuilder.Global.GUI) {
				new PExceptionDialog(ex, com.pfsbuilder.Global.sessionNumber).setVisible(true);
			}
		} finally {
			pOpenButton.setEnabled(true);
			statusLabel.setText("");
			searchButton.setText("Search");
			progressBar1.setVisible(false);
		}
	}

	public void pSearchButon_actionPerformed(ActionEvent e) {
		if (searchButton.getText().equals("Search")) {
			searchButton.setText("Cancel");
			// ////////////////////////////////////////////////
			partitionOffsetTextField.setEnabled(false);
			this.offsetComboBox.removeAllItems();
			// /////////////////////////////////////////////////
			new Thread(this).start();
		} else {
			searchButton.setText("Search");
			// /////////////////////////////////////////////////
			progressBar1.setValue(0);
			progressBar1.setVisible(false);
			partitionOffsetTextField.setEnabled(true);
			// /////////////////////////////////////////////////
		}
	}

	public void JRadioButton1_actionPerformed(ActionEvent e) {
		offsetComboBox.setEnabled(false);
		searchButton.setEnabled(false);
		partitionOffsetTextField.setEnabled(true);
	}

	public void JRadioButton2_actionPerformed(ActionEvent e) {
		if (!pfsFileLabel.getText().equals("")) {
			offsetComboBox.setEnabled(true);
			searchButton.setEnabled(true);
			partitionOffsetTextField.setEnabled(false);
		}
	}

	private void pOffsetComboBoxMouseClicked(MouseEvent evt) {
		if (radioButton2.isEnabled()) {
			radioButton2.setSelected(true);
			JRadioButton2_actionPerformed(null);
		}
	}

	private void jPartitionOffsetTextFieldMouseClicked(MouseEvent evt) {
		radioButton1.setSelected(true);
		JRadioButton1_actionPerformed(null);
	}

	private void pHistoryComboBoxActionPerformed(ActionEvent evt) {
		try {
			if (historyComboBox.getSelectedIndex() > 0) {
				HashMap hashmap = historyVector.get(historyVector.size() - historyComboBox.getSelectedIndex());
				String pfs_file = CommonLib.empty(hashmap.get("pfs_file"));
				String project_file = CommonLib.empty(hashmap.get("project_file"));
				String temp_directory = CommonLib.empty(hashmap.get("temp_directory"));
				String offset = CommonLib.empty(hashmap.get("offset"));
				pfsFileLabel.setText(pfs_file);
				pProjectFileLabel.setText(project_file);
				tempDirectoryLabel.setText(temp_directory);
				radioButton1.setSelected(true);
				radioButton2.setEnabled(true);
				partitionOffsetTextField.setText(offset);
			}
			checkPOpenButton();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}

class POpenDialog_JRadioButton2_actionAdapter implements ActionListener {
	private OpenDialog adaptee;

	POpenDialog_JRadioButton2_actionAdapter(OpenDialog adaptee) {
		this.adaptee = adaptee;
	}

	public void actionPerformed(ActionEvent e) {
		adaptee.JRadioButton2_actionPerformed(e);
	}
}

class POpenDialog_JRadioButton1_actionAdapter implements ActionListener {
	private OpenDialog adaptee;

	POpenDialog_JRadioButton1_actionAdapter(OpenDialog adaptee) {
		this.adaptee = adaptee;
	}

	public void actionPerformed(ActionEvent e) {
		adaptee.JRadioButton1_actionPerformed(e);
	}
}

class POpenDialog_pSearchButton_actionAdapter implements ActionListener {
	private OpenDialog adaptee;

	POpenDialog_pSearchButton_actionAdapter(OpenDialog adaptee) {
		this.adaptee = adaptee;
	}

	public void actionPerformed(ActionEvent e) {
		adaptee.pSearchButon_actionPerformed(e);
	}
}

class POpenDialog_pSelectTempDirectoryButton_actionAdapter implements ActionListener {
	private OpenDialog adaptee;

	POpenDialog_pSelectTempDirectoryButton_actionAdapter(OpenDialog adaptee) {
		this.adaptee = adaptee;
	}

	public void actionPerformed(ActionEvent e) {
		adaptee.pSelectTempDirectoryButton_actionPerformed(e);
	}
}

class POpenDialog_pSelectProjectFileButton_actionAdapter implements ActionListener {
	private OpenDialog adaptee;

	POpenDialog_pSelectProjectFileButton_actionAdapter(OpenDialog adaptee) {
		this.adaptee = adaptee;
	}

	public void actionPerformed(ActionEvent e) {
		adaptee.selectProjectFileButton_actionPerformed(e);
	}
}

class POpenDialog_pOpenPFSButton_actionAdapter implements ActionListener {
	private OpenDialog adaptee;

	POpenDialog_pOpenPFSButton_actionAdapter(OpenDialog adaptee) {
		this.adaptee = adaptee;
	}

	public void actionPerformed(ActionEvent e) {
		adaptee.openPFSButton_actionPerformed(e);
	}
}

class POpenDialog_pOpenButton_actionAdapter implements ActionListener {
	private OpenDialog adaptee;

	POpenDialog_pOpenButton_actionAdapter(OpenDialog adaptee) {
		this.adaptee = adaptee;
	}

	public void actionPerformed(ActionEvent e) {
		adaptee.pOpenButton_actionPerformed(e);
	}
}
